package com.rhzy.springbootfilter.filter;

import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

@Order(1)
@WebFilter(filterName = "globalFilter", urlPatterns = "/*")
public class GlobalFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("filter 初始化了");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("filter 进来了");
        //放行
       // filterChain.doFilter(servletRequest,servletResponse);

        //返回
        OutputStreamWriter osw = new OutputStreamWriter(servletResponse.getOutputStream(),"UTF-8");
        PrintWriter writer = new PrintWriter(osw,true);
        writer.write("{a:a}");
        writer.flush();
        writer.close();
        osw.close();
    }

    @Override
    public void destroy() {
        System.out.println("filter 消毁了");
    }
}
